/**
 * 在body上设置样式变量
 * @param {Object} style 样式的对象
 */
export function setThemeToRoot(style, rewrite = false) {
  let body = document.querySelector('body')
  if (rewrite === true) {
    // 覆盖内联样式
    body.style.cssText = sytleObjToStyleStr(style)
    return
  }
  // 更新和新增内联样式
  setStyleToEle(body, style)
}

/**
 * 将样式对象转换为样式字符串
 * @param {Object} style 样式的对象
 * @returns {String} cssText
 */
function sytleObjToStyleStr(style = {}) {
  if (!Object.keys(style).length) {
    return
  }
  let styleStr = ``
  for (let styleName in style) {
    styleStr += `${styleName}: ${style[styleName]};`
  }
  return styleStr
}

/**
 * 保留原有样式的情况下设置新的样式属性
 * @param {*} ele 元素
 * @param {Object} style 样式对象
 * @returns undefined
 */
function setStyleToEle(ele, style = {}) {
  if (typeof ele === 'string') {
    ele = document.querySelector(ele)
  }
  if (ele instanceof HTMLElement && Object.keys(style).length) {
    for (let styleName in style) {
      ele.style.setProperty(styleName, style[styleName])
    }
  }
}
// plan B
/**
 * 通过滤镜修改主题
 * @param {string} ele 滤镜挂载元素
 * @param {Object} filterOpt 滤镜参数
 */
export function changeThemeByFilter(ele, filterOpt) {
  let {
    blur = 0,
    brightness = 100,
    contrast = 100,
    grayscale = 0,
    hueRotate = 0,
    invert = 0,
    opacity = 100,
    saturate = 100,
    sepia = 0
  } = filterOpt
  let eleList = []
  if (Array.isArray(ele)) {
    eleList = ele.map((e, i) => {
      if (typeof e === 'string') {
        return document.querySelector(e)
      } else if (e instanceof HTMLElement) {
        return e
      }
    })
  } else if (typeof ele === 'string') {
    eleList.push(document.querySelector(ele))
  }
  eleList.forEach((e, i) => {
    if (e instanceof HTMLElement) {
      let filter = `blur(${blur}px) brightness(${brightness}%) contrast(${contrast}%) grayscale(${grayscale}%) hue-rotate(${hueRotate}deg) invert(${invert}%) opacity(${opacity}%) saturate(${saturate}%) sepia(${sepia}%)`
      e.style.setProperty('filter', filter)
      e.style.setProperty('transition', 'filter ease 0.3s')
    }
  })
}
